/*
 * @Author: None
 * @LastEditors: None
 * @Date: 2021-10-19 16:17:06
 * @LastEditTime: 2022-01-26 15:32:26
 */
const { request, format } = require('./utils')
function updateOneOrderStatus(record) {
  // console.log(record)
  if (!record.id) return;
  const stateMap = {
    1: '成功',
    2: '充值中'
  }
  function getStateDesc(state) {
    return stateMap[state] || '失败'
  }
  request(`auto/queryOrderStatusByOrderCreatedAt/${record.created}`, data => {
    // 如果能通过时间找到对应的记录则更新订单状态，否则绑定订单，记录订单创建时间
    const state = record.state;
    const desc = getStateDesc(record.state);
    const orderCreated_at = record.created;
    if (data.orderStatus.length) {
      const r = data.orderStatus[0];
      if (r.state != record.state) {
        // 更新状态表的状态
        request({
          url: `auto/updateOrderStatus/${r.id}`,
          type: 'POST',
          data: {
            state: state,
            desc: desc
          }
        });
      }
    } else {
      // 将记录与状态表一一绑定
      const beginTime = format(record.created);
      const endTime = format(+new Date(record.created) + 120000);
      console.log(beginTime,endTime);
      request({
        url: `auto/queryOrderStatusGtCreatedAt`,
        type: 'post',
        data: {
          beginTime: beginTime,
          endTime: endTime,
          _contains: { robot: getRobotByXxx() },
        }
      }, data => {
        const orderStatus = data.orderStatus[0];
        if (orderStatus) {
          const id = orderStatus.id;
          console.log('查询到订单',id);
          console.log({
            orderCreated_at: format(orderCreated_at),
            state: state,
            desc: desc
          })
          // 插入'状态记录'到状态表
          request({
            url: `auto/updateOrderStatus/${id}`,
            type: 'POST',
            data: {
              orderCreated_at: format(orderCreated_at),
              state: state,
              desc: desc,
            }
          });
        } else {
          console.warn('未查询到订单');
        }
      })
    }
  })
}

// FIXME: 
function getRobotByXxx() {
  return 'autojs';
}

// 更新状态
async function updateOrderStatus(recordList) {
  // console.log(recordList);
  for (let key in recordList) {
    updateOneOrderStatus(recordList[key]);
  }
}
module.exports = {
  summary: '获取订单列表',
  *beforeSendResponse(requestDetail, responseDetail) {
    const newResponse = responseDetail.response;
    if (requestDetail.url.includes('http://www.txiat.cn/client/server/')) {
      // console.log('对比不同')
      const r = newResponse.body.toString();
      const res = JSON.parse(r);
      if (res.code == 0 && res.count > 0) {
        updateOrderStatus(res.data);
      }

      // console.log(res);
      // updateOrderStatus(data);
    }
    return Promise.resolve({ response: newResponse });
  },
  *beforeSendRequest(requestDetail) {
    return Promise.resolve(requestDetail);
  },
  onConnectError(requestDetail, error) {
    console.log('网络连接失败')
  }
};